package cc.io24.knewcafe.boss.service;

import cc.io24.knewcafe.boss.facade.BasicFacade;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.hateoas.PagedResources;

import java.util.ArrayList;
import java.util.List;

public class BaseFacadeService<T> extends BaseService<T> {

    BasicFacade<T> basicFacade ;

    @Override
    public Page<T> getList(T t, Pageable pageable) {
        String sort = StringUtils.replace(pageable.getSort().toString(),":",",");
        sort = StringUtils.replace(sort," ","");
        PagedResources<T> pagedResources = (PagedResources<T>) basicFacade.findAll(pageable.getPageNumber()+"",pageable.getPageSize()+"",sort);
        Pageable pageable1 = PageRequest.of((int)pagedResources.getMetadata().getNumber(),
                (int)pagedResources.getMetadata().getSize());
        List<T> list = new ArrayList<>(pagedResources.getContent());
        Page<T> page = new PageImpl<T>(list,
                pageable1,
                (long)pagedResources.getMetadata().getTotalElements());
        return page;
    }

    @Override
    public T getOne(String id) {
        T t = basicFacade.findById(id);
        return t;
    }

    @Override
    public T insert(T t) {
        return basicFacade.insert(t);
    }

    @Override
    public T update(T t,String id) {
        T t2 = basicFacade.save(t,id);
        return t;
    }

    @Override
    public void deleteById(String id) {
        basicFacade.deleteById(id);
    }

    public BasicFacade<T> getBasicFacade() {
        return basicFacade;
    }

    public void setBasicFacade(BasicFacade<T> basicFacade) {
        this.basicFacade = basicFacade;
    }
}

